//
//  DidUseController.m
//  BigToBig
//
//  Created by guochuangkeshi on 16/4/26.
//  Copyright © 2016年 cn.cloudtp. All rights reserved.
//

#import "DidUseController.h"
//#import "ExpiredCell.h"
#import "xiuQuanModel.h"

static int p = 0;
static int offset = 0;
static int each = 4;

@interface DidUseController ()

@property (strong,nonatomic)NSMutableArray *xiuQuanArray;
@property (strong,nonatomic)UIImageView *imageView;
@end

@implementation DidUseController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.tableView.rowHeight = 106;
    NSMutableArray *xiuQuanArray = [NSMutableArray array];
    self.xiuQuanArray = xiuQuanArray;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self loadData];

    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loaddata1)];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    //    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    NSLog(@"%f",self.tableView.bounds.origin.y);

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (void)loadData{
    
    

    NSLog(@"%f",self.tableView.bounds.origin.y);
    NSUserDefaults* userID = [NSUserDefaults standardUserDefaults];
    NSString *UID = [userID objectForKey:@"userID"];
    
    
//    Reachability *reach = [Reachability reachabilityForInternetConnection];
//    NetworkStatus *status = [reach currentReachabilityStatus];
//    if (status == NotReachable) {
//        
//        
//        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
//        HUD.labelText = @"请检查网络连接";
//        HUD.mode = MBProgressHUDModeText;
//        [HUD hide:YES afterDelay:1.0];
//        
//        return;
//        
//    }
    offset = 0;
    [self.imageView removeFromSuperview];
    [self.xiuQuanArray removeAllObjects];
    
    NSLog(@"%ld",self.xiuQuanArray.count);
    
    NSDictionary *params = @{@"user_id":UID,@"type":@"1",@"status":@"1",@"offset":@"0",@"limit":@"4"};
    [HttpTool postWithURL:@"http://61.135.176.43:6080/bigtobig/ticket/get_all_ticket_by_type_and_status?" params:params success:^(id json) {
        
        NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        NSMutableArray *tempArray = [NSMutableArray array];
        tempArray = dict[@"ticketList"];
        //        NSMutableArray *tempArray = dict[@"ticketList"];
        
        for (int i = 0; i < tempArray.count; i++) {
            
            NSDictionary *dict = tempArray[i];
            
            xiuQuanModel *xiuQuanMD = [xiuQuanModel XiuQuanModelWithDict:dict];
            
            [self.xiuQuanArray addObject:xiuQuanMD];
    
            
        }
        if (tempArray.count == 0) {
            
            NSLog(@"%f",self.view.bounds.origin.y);
            
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
            imageView.image = [UIImage imageNamed:@"not_data"];
            self.imageView = imageView;
            imageView.backgroundColor = [UIColor whiteColor];

            imageView.contentMode = UIViewContentModeCenter;

            [self.tableView addSubview:imageView];
            
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];
            
        });
        
        [self.tableView.mj_header endRefreshing];
        
    } failure:^(NSError *error) {
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            
            MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
            HUD.labelText = @"网络请求失败";
            HUD.mode = MBProgressHUDModeText;
            [HUD hide:YES afterDelay:1.0];
            
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
            imageView.image = [UIImage imageNamed:@"not_data"];
            self.imageView = imageView;
            imageView.backgroundColor = [UIColor whiteColor];
            
            imageView.contentMode = UIViewContentModeCenter;
            
            [self.tableView addSubview:imageView];
            
        });

        
        
    }];
    
//    
}

- (void)loaddata1{
    
    NSUserDefaults* userID = [NSUserDefaults standardUserDefaults];
    NSString *UID = [userID objectForKey:@"userID"];
    
//    Reachability *reach = [Reachability reachabilityForInternetConnection];
//    NetworkStatus *status = [reach currentReachabilityStatus];
//    if (status == NotReachable) {
//        
//        
//        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
//        HUD.labelText = @"请检查网络连接";
//        HUD.mode = MBProgressHUDModeText;
//        [HUD hide:YES afterDelay:1.0];
//        
//        return;
//        
//    }
//    
    offset = offset + each;
    NSString *str = [NSString stringWithFormat:@"%d",offset];
    //    [self.imageView removeFromSuperview];
    
    NSLog(@"%d",self.xiuQuanArray.count);
    
    NSString *count = [NSString stringWithFormat:@"%d",p * 2];
    NSLog(@"%@",count);
    NSDictionary *params = @{@"user_id":UID,@"type":@"1",@"status":@"1",@"offset":str,@"limit":@"4"};
    [HttpTool postWithURL:@"http://61.135.176.43:6080/bigtobig/ticket/get_all_ticket_by_type_and_status?" params:params success:^(id json) {
        
        NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        
        NSMutableArray *xiuQuanArray = dict[@"ticketList"];
        
        for (int i = 0; i < xiuQuanArray.count; i++) {
            
            NSDictionary *dict = xiuQuanArray[i];
            
            xiuQuanModel *xiuQuanMD = [xiuQuanModel XiuQuanModelWithDict:dict];
            
            [self.xiuQuanArray addObject:xiuQuanMD];
            
            
            NSLog(@"%d",xiuQuanArray.count);
            NSLog(@"%@",xiuQuanMD.tickedId);
            NSLog(@"用户%@",xiuQuanMD.userId);
            
            
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];
            
        });
        p++;
        [self.tableView.mj_footer endRefreshing];
//        [self.tableView.mj_header endRefreshing];
    } failure:^(NSError *error) {
        
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
//        [self.tableView.mj_header endRefreshing];
        
        
        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
        HUD.labelText = @"网络请求失败";
        HUD.mode = MBProgressHUDModeText;
        [HUD hide:YES afterDelay:1.0];
        
        
    }];
    
    
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.xiuQuanArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
    NSString *cellID = [NSString stringWithFormat:@"Cell%ld%ld",(long)[indexPath section],(long)[indexPath row]];
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    if (cell==nil) {
        
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    if (indexPath.section < self.xiuQuanArray.count) {
        
        xiuQuanModel *xiuQuanMD = self.xiuQuanArray[indexPath.section];
        
        UIImageView *xiuQuanImageView = [[UIImageView alloc]initWithFrame:cell.contentView.bounds];
        xiuQuanImageView.image = [UIImage imageNamed:@"秀卷1_08"];
        [cell.contentView addSubview:xiuQuanImageView];
        
        UIImageView *ZiImageView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 10, 60, 50)];
        ZiImageView.image = [UIImage imageNamed:@"字_08"];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(13,45, 70, 20)];
        label.text = @"此券可用于路演";
        label.font = [UIFont systemFontOfSize:10.0];
        label.textColor = [UIColor lightGrayColor];
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 73, xiuQuanImageView.bounds.size.width, 0.3)];
        lineView.backgroundColor = [UIColor lightGrayColor];
        
        
        UILabel *unUseLabel = [[UILabel alloc]initWithFrame:CGRectMake(27, lineView.maxY+5, 70, 20)];
        unUseLabel.text = @"已使用";
        unUseLabel.font = [UIFont systemFontOfSize:13.0];
        unUseLabel.textColor = [UIColor lightGrayColor];
        
        UILabel *luYanQuanLabel = [[UILabel alloc]initWithFrame:CGRectMake(160, 10, 70, 30)];
        luYanQuanLabel.text = @"路演专用券";
        luYanQuanLabel.font = [UIFont systemFontOfSize:14.0];
        luYanQuanLabel.textColor = [UIColor grayColor];
        
        UILabel *liveTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(130, 45, 200, 20)];
        NSString *LiveTimeStr = [NSString stringWithFormat:@"有效期至 : %@",xiuQuanMD.expiryDate];
        liveTimeLabel.text = LiveTimeStr;
        liveTimeLabel.font = [UIFont systemFontOfSize:10.0];
        liveTimeLabel.textColor = [UIColor grayColor];
        
        UILabel *idLabel = [[UILabel alloc]initWithFrame:CGRectMake(200, lineView.maxY+5, 100, 20)];
        NSString *IdStr = [NSString stringWithFormat:@"ID:%@",xiuQuanMD.ticketNo];
        idLabel.text = IdStr;
        idLabel.font = [UIFont systemFontOfSize:12.0];
        idLabel.textColor = [UIColor lightGrayColor];
        
        [xiuQuanImageView addSubview:lineView];
        [xiuQuanImageView addSubview:ZiImageView];
        [xiuQuanImageView addSubview:unUseLabel];
        [xiuQuanImageView addSubview:luYanQuanLabel];
        [xiuQuanImageView addSubview:liveTimeLabel];
        [xiuQuanImageView addSubview:idLabel];
        [xiuQuanImageView addSubview:label];
        
    }
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return .1;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
